package com.qianlima.upload.application;

import com.qianlima.upload.common.dto.FileDto;
import com.qianlima.upload.common.dto.ResponseDto;
import com.qianlima.upload.domain.service.FileUploadExec;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @description: 应用层
 * @author：allms
 * @date: 2023/3/22 15:40
 */
@Component
public class FileUploadApp {
    @Resource
    private FileUploadExec fileUploadExec;

    public ResponseDto upload(List<MultipartFile> multipartFileList) {
        List<String> uploadResultList;
        try {
            uploadResultList = fileUploadExec.upload(multipartFileList);
            return ResponseDto.success(uploadResultList);
        } catch (IOException e) {
            return ResponseDto.fail("文件上传失败");
        }
    }

    public ResponseDto fragUpload(FileDto fileDto) {
        try {
            String fileUrl = fileUploadExec.fragUpload(fileDto, false, null);
            return ResponseDto.success(fileUrl);
        } catch (IOException | InterruptedException e) {
            return ResponseDto.fail("文件分片上传失败");
        }
    }

    public ResponseDto fragUploadFile(FileDto fileDto, MultipartFile file) {
        try {
            String fileUrl = fileUploadExec.fragUpload(fileDto, true, file);
            return ResponseDto.success(fileUrl);
        } catch (IOException | InterruptedException e) {
            return ResponseDto.fail("文件分片上传失败");
        }
    }

    public ResponseDto checkFrag(String key, Integer shardTotal) {
        FileDto fileDto = fileUploadExec.checkFrag(key, shardTotal);
        if (fileDto == null) {
            return ResponseDto.fail("文件不存在");
        }
        return ResponseDto.success(fileDto);
    }
}
